// @flow
import React from 'react'
import { Modal, Form, Input, Button, Select, DatePicker, message } from 'antd'
// import styles from './HistoryPop.css'
import moment from 'moment'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const FormItem = Form.Item
const RangePicker = DatePicker.RangePicker
const Option = Select.Option

type Props = {
  userName: string,
  deviceCard: Object,
  form: Object,
  eventTime: number,
  updateEvents: Function,
  removeEventsModal: Function,
  channel_id: string,
  variableNameEn: string,
  checkName: string,
  sensorNameEn: string,
  sensorName: string
}

type State = {
  loading: boolean,
  visible: boolean,
  groupId: string,
  eventType: Array<Object>
}

class AddChartEvent extends React.Component {
  props: Props
  state: State
  showModal: Function
  handleOk: Function
  handleCancel: Function
  handleSubmit: Function
  getEventType: Function

  constructor (props: Object) {
    super(props)
    this.state = {
      loading: false,
      visible: true,
      groupId: this.props.deviceCard.groupId,
      eventType: []
    }
    this.showModal = this.showModal.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.getEventType = this.getEventType.bind(this)
  }

  componentWillMount () {
    this.getEventType()
  }

  handleSubmit (e: Object) {
    e.preventDefault()
    const { form, userName } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      // this.setState({
      //   loading: true
      // })
      // let API = `${__SERVICE_API__}device/events`
      // const eventType = fieldsValue.eventType
      // if (eventType === '故障') {
      //   API = `${__SERVICE_API__}device/events/faults`
      // }
      // if (eventType === '维修') {
      //   API = `${__SERVICE_API__}device/events/maintenances`
      // }
      let API = `${__SERVICE_API__}device/events1/maintenance`
      const { channel_id, variableNameEn, sensorNameEn, sensorName, checkName } = this.props
      const values = {
        ...fieldsValue,
        'componentId': 0, // 后台设定的必须传的值，但没有实际意义
        deviceId : this.props.deviceCard.deviceData.id,
        customerId: this.props.deviceCard.deviceData.customer.id,
        startTime : moment(fieldsValue.rangeTime[0]),
        endTime : moment(fieldsValue.rangeTime[1]),
        creator: userName,
        eventDesc: fieldsValue.eventDesc || '',
        eventType: '故障类型',
        channelId: channel_id,
        variableNameEn: variableNameEn,
        sensorNameEn: sensorNameEn,
        sensorName: sensorName,
        eventPonts: [{
          'channelId': channel_id,
          'checkName': checkName,
          'sensorName': sensorName,
          'sensorNameEn': sensorNameEn,
          'variableNameEn': variableNameEn
        }]
        // checkName: checkName // '通频值__YT111A'
      }
      universalFetch(API, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(values)
      })
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({
              code: json.code,
              message: json.message
            }))
          }
          this.setState({ loading: false, visible: false })
          if (json.code === 200000) {
            message.success('事件添加成功')
            this.setState({
              visible: false
            })
            this.props.removeEventsModal()
            this.props.updateEvents()
          } else {
            message.error('事件添加失败，请重新添加')
          }
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
        })
    })
  }

  getEventType () {
    universalFetch(`${__SERVICE_API__}sys/dicts?pageNum=1&type=eventType`)
    .then(res => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        eventType: json.result
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }

  showModal () {
    this.setState({
      visible: true
    })
  }

  handleOk () {}

  handleCancel () {
    this.setState({ visible: false })
    this.props.removeEventsModal()
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { eventTime } = this.props
    const { eventType } = this.state
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    }
    const { deviceData } = this.props.deviceCard
    const title = '添加事件（' + deviceData.customerName + '/' + deviceData.name + '）'
    return (
      <Modal ref='modal'
        visible={this.state.visible}
        maskClosable={false}
        title={title} onOk={this.handleOk} onCancel={this.handleCancel}
        footer={[
          <Button key='back' type='ghost' onClick={this.handleCancel}>返 回</Button>,
          <Button key='submit' type='primary' loading={this.state.loading} onClick={this.handleOk}>
            提交
          </Button>
        ]}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem
            {...formItemLayout}
            label='事件名称'>
            {getFieldDecorator('eventName', {
              rules: [
                { required: true, message: '请填写事件名称', whitespace: true }
              ]
            })(
              <Input type='text' placeholder='请填写事件名称' />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='事件类型'>
            {getFieldDecorator('type', {
              rules: [
                { required: true, message: '请选择事件类型' }
              ]
            })(
              <Select placeholder='请选择事件类型' showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}>
                {
                  eventType.map((d, i) => {
                    return <Option key={i} value={d.value}>
                      {d.label}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='测点名称'>
            {getFieldDecorator('checkName', {
              initialValue: this.props.checkName
            })(
              <Input type='text' placeholder='请填写测点名称' disabled />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='事件时间'>
            {getFieldDecorator('rangeTime', {
              rules: [
                { required: true, message: '请填写事件时间' }
              ],
              initialValue: [moment(eventTime), moment()]
            })(
              <RangePicker style={{ width: 'auto' }}
                showTime format='YYYY-MM-DD HH:mm:ss' />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='负责人'>
            {getFieldDecorator('owner', {
              rules: [
                { required: true, message: '请输入负责人', whitespace: true }
              ]
            })(
              <Input type='text' placeholder='请输入负责人' />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='处理状态'>
            {getFieldDecorator('eventStatus', {
              rules: [
                { required: true, message: '请选择处理状态' }
              ]
            })(
              <Select placeholder='请选择处理状态' showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}>
                <Option value='未处理'>未处理</Option>
                <Option value='已处理'>已处理</Option>
                <Option value='生成工单'>生成工单</Option>
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='事件描述'>
            {getFieldDecorator('eventDesc')(
              <Input type='textarea' placeholder='请填写事件描述' />
            )}
          </FormItem>
          <Button htmlType='submit' type='primary'
            style={{ position:'absolute', bottom:'10px', right:'16px', zIndex: '2' }}>
            提 交
          </Button>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(AddChartEvent)
